package cn.hc.case1;

import org.apache.zookeeper.*;
import org.junit.Before;

import java.io.IOException;
import java.util.List;

/**
 * @author huangchao E-mail:fengquan8866@163.com
 * @version 创建时间：2024/10/18 22:04
 */
public class DistributeServer {

    // 注意：逗号左右不能有空格
    private String connectString = "master:2181,hadoop141:2181,hadoop-test:2181";
    private int sessionTimeout = 2000;

    private ZooKeeper zkClient;

    public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
        DistributeServer server = new DistributeServer();
        // 1 获取zk连接
        server.getConnect();
        // 2 注册服务器到zk集群
        server.regist(args[0]);
        // 3 启动业务逻辑
        server.business();
    }

    private void business() throws InterruptedException {
        Thread.sleep(Long.MAX_VALUE);
    }

    private void regist(String hostname) throws InterruptedException, KeeperException {
        String create = zkClient.create("/hc/servers/"+hostname, hostname.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);

        System.out.println(hostname + " register success, path:" + create);
    }

    private void getConnect() throws IOException {
        zkClient = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
            @Override
            public void process(WatchedEvent watchedEvent) {
                System.out.println("-----------------------------------");
            }
        });
    }
}
